<?php

namespace App\Jobs;

use Exception;
use App\Models\Genre;
use App\Models\Attendance;
use Illuminate\Bus\Queueable;
use App\Models\Attendance\Report;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class AttendanceReportGenerate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	/**
	 * AttendanceReportGenerate constructor.
	 */
    public function __construct()
    {

    }

	/**
	 * Date: 30/04/2018
	 * @author George
	 * @throws \Throwable
	 */
    public function handle()
    {
		$start = date('Y-m-d 12:00:00', strtotime('-' . (config('system.report.delay') + 1) . ' day'));
		$end = date('Y-m-d 12:00:00', strtotime('-' . config('system.report.delay') . ' day'));
		try {
			// 获取之前的考勤记录
			$attendances = Attendance::with('project', 'schedule', 'user', 'genre')
				->whereBetween('checkout_time', [$start, $end])
				->get();

			if ($attendances->isEmpty()) {
				return false;
			}

			Log::info('Start Processing...');

			// 进行分析
			foreach ($attendances as $attendance) {
				$genres = Cache::remember("projects:{$attendance->project->id}:genres", 60, function () use ($attendance) {
					return Genre::query()->where('project_id', $attendance->project->id)->get();
				});
				// 获取个人的记录
				$record = Report::query()->where('user_id', $attendance->user_id)->first();

				// 如果报表已经存在，则更新属性
				if ($record) {
					if (array_key_exists(substr($attendance->schedule->date, -2), $record->days)) {
						continue;
					}
					$days = $record->days;
					$days[substr($attendance->schedule->date, -2)] = $attendance->genre->code;
					$record->days = $days;
					$record->{$attendance->genre->code} += 1;
					$record->worktime += $attendance->schedule->worktime;
					$record->save();
				} else {
					$attributes = [
						'user_id' => $attendance->user_id,
						'project_id' => $attendance->project_id,
						'name' => $attendance->user->name,
						'position' => $attendance->user->position->name,
						'days' => [
							substr($attendance->schedule->date, -2) => $attendance->genre->code
						],
						'attendance' => '',
						'traing' => '',
						// 总工时
						'worktime' => $attendance->schedule->worktime,
					];

					foreach ($genres as $genre) {
						// 个人月纬度班次统计
						if ($genre->id === $attendance->genre_id) {
							Log::info($genre->id);
							$attributes[$genre->code] = 1;
						} else {
							$attributes[$genre->code] = 0;
						}
						// 添加班次信息
						$attributes['genres'][] = [
							'code' => $genre->code,
							'name' => $genre->name
						];
					}
					// 创建报表
					Report::create($attributes);
				}
			}
			Log::info('Finish!');
		} catch (Exception $exception) {
			Log::error($exception->getMessage());
		}
	}
}
